<template>
  <div class="test-region-container">
    <h2>地区选择组件测试</h2>

    <div class="test-section">
      <h3>测试1: 基本使用（emitPath=true）</h3>
      <RegionCascader
        v-model="regionData1"
        placeholder="请选择省/市/区"
        :emit-path="true"
        @change="handleRegionChange1"
        @update:modelValue="onModelValueUpdate1"
      />
      <el-button @click="testTriggerChange1" type="primary">测试触发change事件</el-button>
      <el-button @click="logCurrentSelection" type="success">记录当前选择</el-button>
      <el-button @click="testDirectUpdate" type="warning">直接更新表单</el-button>
      <div class="result">
        <p>选中值: {{ regionData1 }}</p>
        <p>省份: {{ form1.province }}</p>
        <p>城市: {{ form1.city }}</p>
        <p>区县: {{ form1.district }}</p>
      </div>
    </div>

    <div class="test-section">
      <h3>测试2: 基本使用（emitPath=false）</h3>
      <RegionCascader
        v-model="regionData2"
        placeholder="请选择省/市/区"
        :emit-path="false"
        @change="handleRegionChange2"
      />
      <div class="result">
        <p>选中值: {{ regionData2 }}</p>
        <p>省份: {{ form2.province }}</p>
        <p>城市: {{ form2.city }}</p>
        <p>区县: {{ form2.district }}</p>
      </div>
    </div>

    <div class="test-section">
      <h3>测试3: 初始值设置</h3>
      <el-button @click="setInitialValue">设置初始值</el-button>
      <RegionCascader
        v-model="regionData3"
        placeholder="请选择省/市/区"
        :emit-path="true"
        @change="handleRegionChange3"
      />
      <div class="result">
        <p>选中值: {{ regionData3 }}</p>
        <p>省份: {{ form3.province }}</p>
        <p>城市: {{ form3.city }}</p>
        <p>区县: {{ form3.district }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { RegionCascader } from '@/components/business/region'

  // 测试1: emitPath=true
  const regionData1 = ref<string | number[] | null>('')
  const form1 = reactive({
    province: '',
    city: '',
    district: '',
  })

  const handleRegionChange1 = (value: string | number[] | null, selectedOptions: any[]) => {
    console.log('RegionTest handleRegionChange1 被调用，参数:', { value, selectedOptions })
    console.log('测试1 selectedOptions详情:', JSON.stringify(selectedOptions, null, 2))

    if (value && selectedOptions && selectedOptions.length > 0) {
      // 优先使用selectedOptions获取完整的省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      console.log('测试1 省份对象:', province)
      console.log('测试1 城市对象:', city)
      console.log('测试1 区县对象:', district)

      form1.province = province?.name || province?.label || ''
      form1.city = city?.name || city?.label || ''
      form1.district = district?.name || district?.label || ''
    } else if (value) {
      // 如果没有selectedOptions，尝试从value中解析
      if (Array.isArray(value)) {
        // 如果是数组，取最后一个元素
        const lastItem = value[value.length - 1]
        form1.district = lastItem?.toString() || ''
      } else if (typeof value === 'string') {
        if (value.includes('/')) {
          const codes = value.split('/')
          form1.province = codes[0] || ''
          form1.city = codes[1] || ''
          form1.district = codes[2] || ''
        } else {
          form1.district = value
        }
      } else if (typeof value === 'number') {
        // 处理单个数字值
        form1.district = String(value)
      }
    } else {
      form1.province = ''
      form1.city = ''
      form1.district = ''
    }

    console.log('RegionTest form1 更新后:', form1)
  }

  const testTriggerChange1 = () => {
    console.log('手动触发change事件测试')
    const testValue = '110000/110100/110101'
    const testOptions = [
      { code: '110000', name: '北京市', level: 'province' },
      { code: '110100', name: '北京市', level: 'city' },
      { code: '110101', name: '东城区', level: 'district' },
    ]
    handleRegionChange1(testValue, testOptions)
  }

  // 监听modelValue更新
  const onModelValueUpdate1 = (value: string | number | (string | number)[] | null) => {
    console.log('RegionTest onModelValueUpdate1 被调用，值:', value)
  }

  // 测试直接修改form1的值
  const logCurrentSelection = () => {
    console.log('当前选择的数据:')
    console.log('regionData1:', regionData1.value)
    console.log('form1:', JSON.parse(JSON.stringify(form1)))
  }

  const testDirectUpdate = () => {
    console.log('RegionTest testDirectUpdate 被调用')
    form1.province = '北京市'
    form1.city = '北京市'
    form1.district = '东城区'
    console.log('form1已更新:', JSON.parse(JSON.stringify(form1)))
  }

  // 测试2: emitPath=false
  const regionData2 = ref<string | number[] | null>('')
  const form2 = reactive({
    province: '',
    city: '',
    district: '',
  })

  const handleRegionChange2 = (value: string | number[] | null, selectedOptions: any[]) => {
    console.log('测试2 地区选择变化:', value, selectedOptions)
    console.log('测试2 selectedOptions详情:', JSON.stringify(selectedOptions))

    if (value && selectedOptions && selectedOptions.length > 0) {
      // 优先使用selectedOptions获取完整的省市区信息
      console.log('测试2 使用selectedOptions解析')
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      form2.province = province?.name || province?.label || ''
      form2.city = city?.name || city?.label || ''
      form2.district = district?.name || district?.label || ''
    } else if (value) {
      console.log('测试2 没有selectedOptions，使用值解析')
      // 如果没有选项对象，尝试从值中解析
      if (Array.isArray(value)) {
        // 如果是数组，取最后一个元素
        const lastItem = value[value.length - 1]
        form2.district = lastItem?.toString() || ''
      } else if (typeof value === 'string') {
        form2.district = value
      } else if (typeof value === 'number') {
        // 处理单个数字值
        form2.district = String(value)
      }
    } else {
      form2.province = ''
      form2.city = ''
      form2.district = ''
    }
  }

  // 测试3: 初始值设置
  const regionData3 = ref<string | number[] | null>('')
  const form3 = reactive({
    province: '',
    city: '',
    district: '',
  })

  const handleRegionChange3 = (value: string | number[] | null, selectedOptions: any[]) => {
    console.log('测试3 地区选择变化:', value, selectedOptions)

    if (value && selectedOptions && selectedOptions.length > 0) {
      // 优先使用selectedOptions获取完整的省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      form3.province = province?.name || province?.label || ''
      form3.city = city?.name || city?.label || ''
      form3.district = district?.name || district?.label || ''
    } else if (value) {
      // 如果没有选项对象，尝试从值中解析
      if (Array.isArray(value)) {
        // 如果是数组，取最后一个元素
        const lastItem = value[value.length - 1]
        form3.district = lastItem?.toString() || ''
      } else if (typeof value === 'string') {
        if (value.includes('/')) {
          const codes = value.split('/')
          form3.province = codes[0] || ''
          form3.city = codes[1] || ''
          form3.district = codes[2] || ''
        } else {
          form3.district = value
        }
      } else if (typeof value === 'number') {
        // 处理单个数字值
        form3.district = String(value)
      }
    } else {
      form3.province = ''
      form3.city = ''
      form3.district = ''
    }
  }

  const setInitialValue = () => {
    // 设置一个初始值（假设是广东省/深圳市/南山区）
    regionData3.value = '440000/440300/440305'

    // 手动触发change事件处理函数，模拟组件的change事件
    // 由于我们设置了完整路径，需要解析成选项对象
    const codes = regionData3.value.split('/')
    const selectedOptions = [
      { code: '440000', name: '广东省', level: 'province' },
      { code: '440300', name: '深圳市', level: 'city' },
      { code: '440305', name: '南山区', level: 'district' },
    ]
    handleRegionChange3(regionData3.value, selectedOptions)
  }
</script>

<style scoped>
  .test-region-container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }

  .test-section {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid #eee;
    border-radius: 4px;
  }

  .result {
    margin-top: 15px;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 4px;
  }

  .result p {
    margin: 5px 0;
  }
</style>
